package com.aijk.web.admin.controller;

import com.aijk.base.entity.PagingRequest;
import com.aijk.ehm.api.EhmCompanyApi;
import com.aijk.ehm.model.vo.EhmCompanyVo;
import com.aijk.ehm.sys.api.SysAdminApi;
import com.aijk.ehm.sys.model.SysAdmin;
import com.aijk.web.admin.RetMsg;
import com.aijk.web.admin.shiro.ShiroDbRealm;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * <p>
 * 基础控制器
 * </p>
 */
public class BaseController {

    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;
    @Autowired
    private SysAdminApi adminApi;

    private ShiroDbRealm.ShiroUser shiroUser;

    private SysAdmin currentUser;

    @Autowired
    private EhmCompanyApi ehmCompanyApi;

    @InitBinder
    public void InitBinder(WebDataBinder dataBinder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    protected ShiroDbRealm.ShiroUser getShiroUser() {
        Subject currentUser = SecurityUtils.getSubject();
        return currentUser.getPrincipals() != null ? (ShiroDbRealm.ShiroUser) currentUser.getPrincipals().getPrimaryPrincipal() : null;
    }

    protected SysAdmin getCurrentUser() {
        return adminApi.get(getShiroUser().getUserId());
    }

    /**
     * 体检中心权限
     * @return
     */
    protected boolean isSubCompany() {
        SysAdmin sysAdmin = getCurrentUser();
        if (getCurrentUser().getCompanyId() != null && getCurrentUser().getCompanyId().intValue() > 0){
            return true;
        }
        return false;
    }

    /**
     * 单位权限
     * @return
     */
    protected boolean isCompany() {
        EhmCompanyVo ehmCompanyVo = ehmCompanyApi.findOne(getCurrentUser().getCompanyId());
        Integer status = ehmCompanyVo.getStatus() & 0xff;
        if(status != 10){
            return true;
        }
        return false;
    }


    /**
     * <p>
     * <p>
     * 获取分页对象
     * <p>
     * </p>
     */
    protected <T> PagingRequest getPage() {
        return getPage(10);
    }

    /**
     * <p>
     * <p>
     * 获取分页对象
     * <p>
     * </p>
     *
     * @param size 每页显示数量
     * @return
     */
    protected PagingRequest getPage(int size) {
        int _size = size, _index = 1;
        if (request.getParameter("_size") != null) {
            _size = Integer.parseInt(request.getParameter("_size"));
        }
        if (request.getParameter("_index") != null) {
            _index = Integer.parseInt(request.getParameter("_index"));
        }
        _index = _index / size + 1;
        if (_index < 1) {
            _index = 1;
        }

        return new PagingRequest(_index, _size);
    }

    /**
     * <p>
     * 转换为 bootstrap-table 需要的分页格式 JSON
     * </p>
     *
     * @param page 分页对象
     * @return
     */
    protected String jsonPage(PageInfo<?> page) {
        JSONObject jo = new JSONObject();
        jo.put("total", page.getTotal());
        jo.put("rows", page.getList());
        return toJson(jo);
    }

    protected String json(String code, String msg) {
        JSONObject json = new JSONObject();
        json.put("code", code);
        json.put("msg", msg);
        return json.toJSONString();
    }


    /**
     * 返回 JSON 格式对象
     *
     * @param object 转换对象
     * @return
     */
    protected String toJson(Object object) {
        return JSON.toJSONString(object, SerializerFeature.BrowserCompatible);
    }

    /**
     * 返回 JSON 格式对象
     *
     * @param object 转换对象
     * @param format 序列化特点
     * @return
     */
    protected String toJson(Object object, String format) {
        if (format == null) {
            return toJson(object);
        }
        return JSON.toJSONStringWithDateFormat(object, format, SerializerFeature.WriteDateUseDateFormat);
    }

    protected String redirect(String name) {
        return "redirect:" + name;
    }

    @ExceptionHandler
    public String exceptionHandle(HttpServletRequest request, Exception ex) {
        String resultViewName = "error/500";
        // BindingResult result
        // 记录日志
        logger.error(ex.getMessage());

        String xRequestedWith = request.getHeader("X-Requested-With");
        if (StringUtils.isNotBlank(xRequestedWith)) {
            if (ex instanceof UnauthorizedException) {
                // ajax请求
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("code", "1");
                jsonObject.put("msg", "您没有足够的权限执行该操作");
                request.setAttribute("result", jsonObject.toJSONString());
                resultViewName = "error/unauthorized";
            } else {
                if (ex instanceof BindException) {
                    BindException bex = (BindException) ex;
                    BindingResult result = bex.getBindingResult();
                    if (result.getAllErrors().size() > 0) {
                        request.setAttribute("result", JSONObject.toJSONString(RetMsg.failed(result.getAllErrors().get(0).getDefaultMessage())));
                    } else {
                        request.setAttribute("result", JSONObject.toJSONString(RetMsg.failed("系统错误")));
                    }
                }

                resultViewName = "error/ajax";
            }
        } else {
            if (ex instanceof UnauthorizedException) {
                resultViewName = "error/unauthorized";
            }
        }
        return resultViewName;
    }
}